<?php
// +----------------------------------------------------------------------
// | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
// +----------------------------------------------------------------------
// | File name: Repay.php
// +----------------------------------------------------------------------
// | Author: ljf
// +----------------------------------------------------------------------
// | Description: 还款逻辑trait
// +----------------------------------------------------------------------
// | Others: 其他内容的说明
// +----------------------------------------------------------------------
// | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
// +----------------------------------------------------------------------
// | 1.Date: 2019/1/10 Author: ljf Modification: 创建
// +----------------------------------------------------------------------

namespace App\Models\Traits;


use App\Facades\MoneyPlatformRequestFacade;
use App\Models\RepayRecord as RepayRecordModel;
use App\Models\RepayRecordCommon;
use App\Models\RepayRecordMoney;
use App\Models\RepayRecordMonth;
use App\Models\RepayReliefRecordModel;
use App\Models\User;
use App\Models\UserGlobal;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

trait RepaySummary
{

    /**
     * Description:获取当前用户的当前还款的repaysummary记录
     * Author:lijiafei
     * @param $user_id
     * @return mixed
     */
    public static function getUserCurrentRepay($user_id){
        return self::where('uid',$user_id)->where('status',self::STATUS_ONE)->first();
    }

    /**
     * Description:还当期获取当期数据
     * Author:lijiafei
     * @param $user_id int 用户id
     * @return \App\Models\RepaySummary|bool
     */
    public static function getRepaySummaryLog($user_id){
        //获取用户最后一次借款的数据
        $repaySummary = self::where('uid',$user_id)
            ->with(['recordOne'=>function($q){
                $q->where('status','<>',RepayRecordModel::STATUS_FOUR);
                $q->where('pay_off','=',RepayRecordModel::PAY_OFF_ONE);
            },'recordOne.money','recordOne.month','recordOne.common'])
            ->where('status',self::STATUS_ONE)
            ->first();
        if(!isset($repaySummary->recordOne)){
            return false;
        }
        return $repaySummary;
    }

    /**
     * Description:获取全部还清的数据,没有则创建一条记录
     * Author:lijiafei
     * @param $summary_id int repay_summary 表的id
     * @param $user_id int 用户id
     * @return RepaySummary|bool repaySummary的model
     */
    public static function getAllRepayLog($summary_id,$user_id){
        //获取用户最后一次借款的数据
        $repaySummary = self::where('id',$summary_id)
            ->with(['recordOne'=>function($q){
                $q->where('status','<>',RepayRecordModel::STATUS_FOUR);
                $q->where('pay_off','=',RepayRecordModel::PAY_OFF_TWO);
            },'recordOne.money','recordOne.month','recordOne.common'])
            ->first();
        if(!$repaySummary->recordOne){
            $res = self::createAllRepayLog($summary_id);
            if(!$res){
                return false;
            }
            //获取用户最后一次借款的数据
            $repaySummary = self::where('id',$summary_id)
                ->with(['recordOne'=>function($q){
                    $q->where('status','<>',RepayRecordModel::STATUS_FOUR);
                    $q->where('pay_off','=',RepayRecordModel::PAY_OFF_TWO);
                },'recordOne.money','recordOne.month','recordOne.common'])
                ->first();
        }
        return $repaySummary;
    }

    /**
     * 不管逐期还 全部还清,获取处理中的最后一条数据
     */
    public static function getRepayLastLog($user_id){
        //获取用户最后一次借款的数据
        $repaySummary = self::where('uid',$user_id)
            ->with(['recordOne'=>function($q){
//                $q->where('status','<>',RepayRecordModel::STATUS_FOUR);
                $q->where('pay_off','=',RepayRecordModel::PAY_OFF_TWO);
//                $q->where('status','<>',RepayRecordModel::STATUS_THREE);//去除全部结清失败的
                $q->where('status','=',RepayRecordModel::STATUS_TWO);
            },'recordOne.money','recordOne.month','recordOne.common'])
            ->where('status',self::STATUS_ONE)
            ->first();
        if(!isset($repaySummary->recordOne)){
            $repaySummary = self::where('uid',$user_id)
                ->with(['recordOne'=>function($q){
                    $q->where('status','<>',RepayRecordModel::STATUS_FOUR);
                    $q->where('pay_off','=',RepayRecordModel::PAY_OFF_ONE);
                },'recordOne.money','recordOne.month','recordOne.common'])
                ->where('status',self::STATUS_ONE)
                ->first();
        }
        return $repaySummary;
    }


    /**
     * Description:是否可以全部还清
     * Author:lijiafei
     * @param $repayRecord RepayRecordModel 模型
     * @return boolean
     */
    public static function isAllRepay($repayRecord){
        //判断是否有全部还清这条记录
        $res = RepayRecordModel::where('summary_id',$repayRecord->summary_id) -> where('pay_off',RepayRecordModel::PAY_OFF_TWO)->first();
        if($res){
            return true;
        }
        if($repayRecord->month->status == RepayRecordMonth::STATUS_FOUR && $repayRecord->month->amount > 0){
            return false;
        }
        if($repayRecord->money->status == RepayRecordMoney::STATUS_FOUR){
            return false;
        }
        return true;
    }

    /**
     * Description:是否可以还当期
     * Author:lijiafei
     * @param $summary_id int repay_summary.id
     * @return boolean
     */
    public static function isCurrentRepay($summary_id){
        //判断是否有全部还清这条记录
        $res = RepayRecordModel::where('summary_id',$summary_id) -> where('pay_off',RepayRecordModel::PAY_OFF_TWO)->where('status',2)->first();
        if(!$res){
            return true;
        }
        return false;
    }

    /**
     * Description:创建全部还清的record表数据,新增一条记录
     * 创建repay_record,record_money,record_common表记录,修改repay_summary表的period为0;
     * Author:lijiafei
     * @param $summary_id int repay_summary表的id
     * @return boolean
     */
    public static function createAllRepayLog($summary_id){
        DB::beginTransaction();
        try{
            $repayInfo = self::select('id','period_count','period','loan_id','rate','amount','uid')->where('id',$summary_id)->first();
            //创建repay_record表数据
            $recordData = self::recordData($summary_id,$repayInfo);
            $record = RepayRecordModel::create($recordData,$repayInfo);
            //money表数据
            $moneyData = self::moneyData($summary_id,$repayInfo->loan_id,$record);
            if(!$moneyData)return false;
            $money = $record->money()->create($moneyData);

            //common数据
            $commonData = self::commonData($summary_id,$repayInfo,$record,$moneyData);
            $common = $record->common()->create($commonData);

            //生成一个空的month数据
            $monthData = self::monthData($summary_id,$record);
            $month = $record->month()->create($monthData);

            //总表改变当前的期数为0
//            self::where('id',$summary_id)->update(['period' => 0]);
            DB::commit();
            return true;
        }catch (\Exception $e){
            Log::debug('创建全部全清的数据是出错' . $e->getMessage());
            DB::rollBack();
            return false;
        }

    }

    /**
     * Description:生成record表的数据
     * Author:lijiafei
     * @param $summary_id
     * @return mixed
     */
    protected static function recordData($summary_id,$repayInfo){
        $amount = RepayRecordModel::select() -> where('summary_id',$summary_id)->where('status','<>',RepayRecordModel::STATUS_FOUR)->where('pay_off',RepayRecordModel::PAY_OFF_ONE)->sum('amount');
        $amount = intval($amount);
        $recordInfo['uid'] = $repayInfo->uid;
        $recordInfo['summary_id'] = $summary_id;
        $recordInfo['bank_cards_id'] = 0;
        $recordInfo['period'] = 0;
        $recordInfo['amount'] = bcdiv($amount,100,2);//未还的全部的本金
        $recordInfo['pay_off'] = RepayRecordModel::PAY_OFF_TWO;
        $recordInfo['normal_date'] = Carbon::now()->toDateTimeString();
        return $recordInfo;
    }

    /**
     * 生成money的数据
     */
    protected static function moneyData($summary_id,$loan_id,$record){
        //农信的和光大的金额为0
        $data = self::getRepaymentPlan($loan_id,$summary_id);
        $recordMoney['uid'] = $record->uid;
        $recordMoney['summary_id'] = $summary_id;
        $recordMoney['record_id'] = $record->id;
        $recordMoney['bank_cards_id'] = 0;
        $recordMoney['trade_no'] = 0;
        $recordMoney['period'] = 0;
        $recordMoney['lending_money'] = $data['lending_money']; //利息
        $recordMoney['fines_money'] = $data['fines_money']; //罚息
        $recordMoney['repayment_money'] = $data['repayment_money']; //手续费
        $is_channel = self::getLoanChannel($summary_id);
        if(false == $is_channel){
            //status = 4
            $recordMoney['status'] = RepayRecordMoney::STATUS_FOUR;
        }
        return $recordMoney;
    }

    /**
     * month数据
     */
    protected static function monthData($summary_id,$record){
        $recordMonth['uid'] = $record->uid;
        $recordMonth['summary_id'] = $summary_id;
        $recordMonth['record_id'] = $record->id;
        $recordMonth['bank_cards_id'] = 0;
        $recordMonth['trade_no'] = 0;
        $recordMonth['amount'] = 0;
        $recordMonth['period'] = 0;
        $recordMonth['status'] = RepayRecordMonth::STATUS_ONE;
        return $recordMonth;
    }

    /**
     * common数据
     */
    protected static function commonData($summary_id,$repayInfo,$record,$moneyData){
        $recordCommon['uid'] = $record->uid;
        $recordCommon['summary_id'] = $summary_id;
        $recordCommon['record_id'] = $record->id;
        $recordCommon['bank_cards_id'] = 0;
        $recordCommon['trade_no'] = 0;
        $recordCommon['period'] = 0;
        //计算提前还清手续费
        $info = Repay::repaymentMoney($repayInfo->period,$summary_id);
        $info = bcsub($info,$moneyData['repayment_money'],2);//合计-资方的=公共的
        //2019年2.27 确认 公共的手续费要减去资方提前还清的利息 罚息 手续费  才是公共的手续费
        $info = bcsub($info,$moneyData['lending_money'],2);
        $info = bcsub($info,$moneyData['fines_money'],2);
        $recordCommon['repayment_money'] = $info;
        return $recordCommon;
    }

    /**
     * 生成createTradeNo
     * @param $uid int 用户id
     * @param $type string 类型
     * @return string 生成的订单
     */
    public static function createTradeNo($uid,$type){
        $current = Carbon::now()->timestamp;
        $tradeNo = md5($uid . $current . $type . mt_rand(1, 99999));
        return $tradeNo;
    }

    /**
     * 判断是否可以删除全部还清记录
     */
    public static function deleteAllRepay($uid){
        $repayInfo = self::getRepayLastLog($uid);
        if($repayInfo->recordOne->pay_off == RepayRecordModel::PAY_OFF_TWO){
            //判断是否可以删除
            if($repayInfo->recordOne->money->status != RepayRecordCommon::STATUS_FOUR){
                //删除记录
                RepayRecordModel::destroy($repayInfo->recordOne->id);
                RepayRecordMonth::where('record_id',$repayInfo->recordOne->id)->delete();
                RepayRecordCommon::where('record_id',$repayInfo->recordOne->id)->delete();
                RepayRecordMoney::where('record_id',$repayInfo->recordOne->id)->delete();
            }
        }
    }

    /**
     * 保存银行卡信息
     * @param $bank_card_id int 银行卡id
     * @return boolean
     */
    public static function saveBankInfo($bank_card_id,$user_id = 0){
        //record,month,common,money的bank_cards_id
        if($user_id == 0){
            $user_id = auth('api')->user()->id;
        }
        $updateData = ['bank_cards_id' => $bank_card_id];
        $summary_id = self::where('uid',$user_id)->where('status',self::STATUS_ONE)->value('id');
        DB::beginTransaction();
        try{
            RepayRecordModel::where('summary_id',$summary_id)->whereIn('status',[RepayRecordModel::STATUS_ONE,RepayRecordModel::STATUS_THREE])->update($updateData);
            RepayRecordMonth::where('summary_id',$summary_id)->whereIn('status',[RepayRecordMonth::STATUS_ONE,RepayRecordMonth::STATUS_THREE])->update($updateData);
            RepayRecordCommon::where('summary_id',$summary_id)->whereIn('status',[RepayRecordCommon::STATUS_ONE,RepayRecordCommon::STATUS_THREE])->update($updateData);
            RepayRecordMoney::where('summary_id',$summary_id)->whereIn('status',[RepayRecordMoney::STATUS_ONE,RepayRecordMoney::STATUS_THREE])->update($updateData);
            DB::commit();
            return true;
        }catch (\Exception $e){
            Log::debug('还款:更新还款记录的银行卡出错' . $e->getMessage());
            DB::rollBack();
            return false;
        }
    }

    /**
     * Description:
     * Author:lijiafei
     * @param $user_id "用户标识"
     * @return bool true => 可以放款 false => 正在还款中
     */
    public static function checkRepay($user_id)
    {
        $user_info = User::find($user_id);
        if(empty($user_info)){
            return false;
        }
        $userGlobal = isset($user_info->user_global->global_status) ? $user_info->user_global->global_status : 0;
        if(UserGlobal::STATUS_REPAY_INIT == $userGlobal
            || UserGlobal::STATUS_REPAY_ING == $userGlobal
            || UserGlobal::STATUS_REPAY_FAILURE == $userGlobal
            || UserGlobal::STATUS_REPAY_SUCCESS == $userGlobal){
            return false;
        }
        $result = RepayRecordModel::where('uid',$user_id)->where('status','<>',RepayRecordModel::STATUS_FOUR)->first();
        if($result){
            return false;
        }
        return true;
    }

    /**
     * Description:调用队列的时候更新用户全局状态为放款中 dispatch
     * Author:lijiafei
     * @param $record_id int repay_record表的id
     * @param $uid int 用户id
     * @param int $summary_id repay_summary表的id
     * @param int $period 期数
     * @param string $model 要修改的模型名称
     * @param int $repay_type 自动还是手动
     */
    public static function setRepayStatus($record_id,$uid,$summary_id = 0,$period = -1,$model = '',$repay_type = RepayRecordModel::REPAY_TYPE_MANUAL){
        $updateRecord = [
            'status' => RepayRecordModel::STATUS_TWO,
            'buckle_type' => RepayRecordModel::BUCKLE_TYPE_NONE,
        ];
        UserGlobal::where('uid',$uid)->update(['global_status' => UserGlobal::STATUS_REPAY_ING]);
        if($summary_id != 0 && -1 != $period && $repay_type != 0){
            $update = ['repay_type' => $repay_type];
            switch ($model){
                case 'money':
                    RepayRecordMoney::where('record_id',$record_id)->update($update);
                case 'month':
                    RepayRecordMonth::where('record_id',$record_id)->update($update);
                case 'common':
                    RepayRecordCommon::where('record_id',$record_id)->update($update);
                default:
                    //把总记录改为最后一次调用的方式
                    $updateRecord['repay_type'] = $repay_type;
            }
        }
        RepayRecordModel::where('id',$record_id)->update($updateRecord);
    }


    public static function checkApi($summary_id,$uid){
        //判断是否达到当日最大次数
        $is_send_api = self::checkApiNumber($summary_id,$uid,self::COMMON_API);
        if(!$is_send_api){
            return false;
        }

        //判断是否达到当日最大次数
        $is_send_api = self::checkApiNumber($summary_id,$uid,self::MONEY_API);
        if(!$is_send_api){
            return false;
        }
        return true;
    }

    /**
     * Description:判断平台当日时候达到最大
     * Author:lijiafei
     * @param $summary_id int repay_summary表的id
     * @param $uid int 用户id
     * @param $model
     * @param $type 1 获取 2 设置
     * @return bool true|false true => 可以请求 false => 不可以请求
     */
    public static function checkApiNumber($summary_id,$uid,$model,$type = 1){
        $today = Carbon::today()->toDateString();
        $key = $today  . $uid . $model;
        $number = \Illuminate\Support\Facades\Cache::store('redis')->get($key);
        $number = empty($number) ? 0 : $number;
        if($type == 1){
            //获取
            switch ($model){
                case self::MONEY_API:
                    if($number >= self::MONEY_API_NUMBER){
                        return false;
                    }
                    break;
                case self::COMMON_API:
                    if($number >= self::COMMON_API_NUMBER){
                        return false;
                    }
                    break;
            }
            return true;
        }else if($type == 2){
            //自增1
            $number++;
            return \Illuminate\Support\Facades\Cache::store('redis')->set($key,$number,60*60*24);
        }

    }

    /**
     * Description: 简单获取罚息,必须为逾期订单, 使用前请仔细查看该方法需要参数
     * Author: Gxs
     * @param RepayRecord $record
     * @return array
     */
    public static function getSimpleFines($record)
    {
        //原卡贷数据(晋商/新光大)和新数据逻辑一致
        $days = self::getNotSuccessFinesDays($record);
        if (empty($record['loan_channel']) || 'LCC201709190010' == $record['loan_channel']) {
            //新数据
            if (RepayRecordMoney::STATUS_FOUR == $record['money_status']) {
                $fines_money = 0;
                $money_fines_money = 0;
                $common_fines_money = 0;
            } else {
                $money_fines_money = $money_fines = self::getMoneyFines($record['loan_id'],$record['record_period']); //资方罚息
                $fines_money =  bcdiv(bcmul(bcmul($record['fines_rate'], $record['summary_amount'],8),$days,2), 100, 2); #总罚息
                $common_fines_money = bcsub($fines_money, $money_fines_money, 2);
            }
        } else {
            //原卡贷数据
            //非晋商
            //判断
            if (RepayRecordMoney::STATUS_FOUR == $record['common_status']) {
                $fines_money = 0;
                $money_fines_money = 0;
                $common_fines_money = 0;
            } else {
                $money_fines_money = 0;
                $fines_money =  bcdiv(bcmul(bcmul($record['fines_rate'], $record['summary_amount'],8),$days,2), 100, 2); #总罚息
                $common_fines_money = bcsub($fines_money, $money_fines_money, 2);
            }
        }
        return [
            'fines_money' => $fines_money, //总罚息
            'common_fines_money' => $common_fines_money, //公共罚息
            'money_fines_money' => $money_fines_money, //资方罚息
        ];
    }

    /**
     * Description:计算公共接口的实时罚息和资方的罚息(公共平台罚息 = 罚息*总金额*逾期天数-资方的罚息)
     * Author:lijiafei
     * @param $normal_time 2019/2/28 下午1:57 正常还款时间
     * @param $fines_rate double 罚息
     * @param $amount double 借款总金额
     * @param $common_id int repay_record_common表的id
     * @return array
     */
    public static function getFines($normal_time,$fines_rate,$amount,$common_id){
        $return = [
            'fines_money' => 0, //公共罚息+资方罚息
            'common_fines_money' => 0,//公共罚息
            'money_fines_money' => 0,//资方罚息
            'relief_amount' => 0,//减免金额
        ];
        $common = RepayRecordCommon::select(['id','summary_id','period','record_id'])->find($common_id);
        //查询当前期的情况
        $recordInfo = RepayRecordModel::with(['money','month','common'])
            ->where('id',$common->record_id)
            ->first();
        $day_num = self::getFinesDate($recordInfo);
        if($day_num <= 0){
            //没有逾期,费用为0
            return $return;
        }
        if($recordInfo->status == RepayRecordModel::STATUS_FOUR){
            //已经还款,去里面的数据
            $return = [
                'fines_money' => bcadd($recordInfo->money->fines_money,$recordInfo->common->fines_money,2), //公共罚息+资方罚息
                'common_fines_money' => $recordInfo->common->fines_money,//公共罚息
                'money_fines_money' => $recordInfo->money->fines_money,//资方罚息
                'relief_amount' => $recordInfo->common->relief_amount,//减免金额
            ];
            return $return;
        }else{
            //没有还款,计算罚息
            $fines_money =  bcmul(bcmul($fines_rate, $amount,8),$day_num,2);
            $return['fines_money'] = $fines_money;
            //todo 判断是否是农信
            $is_channel = self::getLoanChannel($recordInfo->summary_id);
            if(false == $is_channel){
                $return = [
                    'fines_money' => $fines_money,
                    'common_fines_money' => $fines_money,//公共罚息
                    'money_fines_money' => 0,//资方罚息
                    'relief_amount' => 0,//资方罚息
                ];
            }else{
                //判断是否有资方扣款成功或者进行中的记录,如果有使用表中的fines_money,没有则请求接口进行获取
                if(RepayRecordMoney::STATUS_FOUR == $recordInfo->money->status || RepayRecordMoney::STATUS_TWO == $recordInfo->money->status){
                    $return['money_fines_money'] = $recordInfo->money->fines_money;
                    $return['common_fines_money'] = bcsub($return['fines_money'],$return['money_fines_money'],2);
                }else{
                    //通过对方的接口获取数据
                    $money_fines_money = self::getMoneyFines($recordInfo->loan_id,$recordInfo->period);
                    $return['money_fines_money'] = $money_fines_money;
                    $return['common_fines_money'] = bcsub($return['fines_money'],$return['money_fines_money'],2);
                }
            }
            //把减免金额增加上
            $relief_amount = $recordInfo->common->relief_amount;
            if(0 == $relief_amount){
                //获取当前用户的金额
                $relief_amount = RepayReliefRecordModel::getReliefAmount($recordInfo->money->loan_id,$recordInfo->period);
            }
            if(0 < $relief_amount){
                $return['common_fines_money'] = $return['common_fines_money'] - $relief_amount;
                $return['fines_money'] = $return['fines_money'] - $relief_amount;
                $return['relief_amount'] = $relief_amount;
            }

            if($return['common_fines_money'] < 0){
                $return['common_fines_money'] = 0;
            }

            if(0 > $return['fines_money']){
                $return['fines_money'] = 0;
            }
        }
        return $return;
    }

    /**
     * Description: 获取资方不成功的逾期天数
     * Author: Gxs
     * @param RepayRecord $record 包含loan_channel,money_status,common_status,normal_date
     * @return int
     */
    public static function getNotSuccessFinesDays($record)
    {
        $current_date = Carbon::now()->format('Y-m-d');
        $days = Carbon::parse($record['normal_date'])->diffInDays($current_date, false);
        return $days < 0 ? 0 : $days;
    }


    /**
     * 计算天数
     */
    public static function getFinesDate($recordInfo){
        $now_time = Carbon::now()->toDateString();
        if(RepayRecordMoney::STATUS_FOUR == $recordInfo->money->status){
            $is_channel = self::getLoanChannel($recordInfo->summary_id);
            if($is_channel){
                $loan_id = $recordInfo->relationSummary->loan_id;
                $period = $recordInfo->period;
                $repay_date = $recordInfo->money->repay_date;
                if(empty($repay_date)){
                    $data = self::mapMoneyDataFromThirdApi($loan_id,$period);
                    if($data){
                        $actualRepayDate = isset($data['actualRepayDate']) ? $data['actualRepayDate'] : $now_time;
                        $repay_date = Carbon::parse($actualRepayDate)->toDateString();
                    }
                }
                if(!empty($repay_date)){
                    $now_time = $repay_date;
                }

            }
        }
        $day_num = count_days($now_time,$recordInfo->normal_date);
        return $day_num < 0 ? 0 : $day_num;
    }

    /**
     * 计算资方的还款计划表的罚息
     * @param $loan_id int jiekuan id
     * @param $period int 当前期数
     * @return double 金额
     */
    public static function getMoneyFines($loan_id,$period){
        $data['loanId'] = $loan_id;
        $data['period'] = $period;
        $res = MoneyPlatformRequestFacade::getRepayPlan($data);
        if(!$res){
            return 0;
        }
        if(isset($res['data']['penaltyAmount'])){
            return $res['data']['penaltyAmount'];
        }else{
            return 0;
        }
    }


    /**
     * 通过loan_id获取提前还清的金额信息
     */
    public static function getRepaymentPlan($loan_id,$summary_id){
        $is_channel = self::getLoanChannel($summary_id);
        if(false == $is_channel){
            return [
                'lending_money' => 0,
                'fines_money' => 0,
                'repayment_money' => 0,
            ];
        }
        $res = MoneyPlatformRequestFacade::getRepaymentPlan($loan_id);
        $data = isset($res['data']) ? $res['data']:[];
        $returnData['lending_money'] = isset($data['interestAmount']) ? $data['interestAmount'] : 0; //利息
        $returnData['fines_money'] = isset($data['penaltyAmount']) ? $data['penaltyAmount'] : 0; //罚息
        $returnData['repayment_money'] = isset($data['serviceAmount']) ? $data['serviceAmount'] : 0; //手续费
        $returnData['amount'] = isset($data['principalAmount']) ? $data['principalAmount'] : 0; //提前还款本金
        return $returnData;
    }

    /**
     * Description:如果已还,可用此方法获取已还的各个金额
     * Author:lijiafei
     * @param RepayRecord $recordInfo model
     * @return array
     */
    public static function getYihuanMoney(RepayRecordModel $recordInfo)
    {
        $money_status = $recordInfo->money->status;
        $month_status = $recordInfo->month->status;
        $common_status = $recordInfo->common->status;
        $summary=$recordInfo->relationSummary;
        //已还本金 已还利息 已还贷后管理费,已还资方罚息,已还平台罚息,已还其他费用(月保费)
        $amount = 0;
        $lending_money = 0;
        $manage_money = 0;
        $money_fines_money = 0;
        $common_fines_money = 0;
        $month_money = 0;
        //本金是资方接口
        if($money_status == RepayRecordMoney::STATUS_FOUR){
            if($summary->loan_channel != 'LCC201709190010' && $summary->data_type == \App\Models\RepaySummary::DATA_TYPE_TWO && $common_status != \App\Models\RepayRecordCommon::STATUS_FOUR){
                //非晋商的本金是随着公共一起扣的
                $amount=0;
            }else{
                $amount = bcadd($amount,$recordInfo->amount,2);
            }
            $lending_money = bcadd($lending_money,$recordInfo->money->lending_money,2);
            $money_fines_money = bcadd($money_fines_money,$recordInfo->money->fines_money,2);
            $manage_money = bcadd($manage_money,$recordInfo->money->manage_money,2);
        }
        if($month_status == RepayRecordMonth::STATUS_FOUR){
            $month_money = bcadd($month_money,$recordInfo->month->amount,2);
        }
        if($common_status == RepayRecordCommon::STATUS_FOUR){
            $lending_money = bcadd($lending_money,$recordInfo->common->lending_money,2);
            $common_fines_money = bcadd($common_fines_money,$recordInfo->common->fines_money,2);
            $manage_money = bcadd($manage_money,$recordInfo->common->manage_money,2);
        }

        //判断是否是有全部结清
        $money_repayment_money = 0;
        $common_repayment_money = 0;
        if($recordInfo->pay_off == RepayRecordModel::PAY_OFF_TWO){
            if($recordInfo->money->status == RepayRecordMoney::STATUS_FOUR){
                $money_repayment_money = $recordInfo->money->where('status',RepayRecordMoney::STATUS_FOUR)->where('period',0)->where('summary_id',$recordInfo->summary_id)->sum('repayment_money');
                $money_repayment_money = bcdiv($money_repayment_money,100,2);
            }
            if($recordInfo->common->status == RepayRecordCommon::STATUS_FOUR){
                $common_repayment_money = $recordInfo->common->where('status',RepayRecordMoney::STATUS_FOUR)->where('period',0)->where('summary_id',$recordInfo->summary_id)->sum('repayment_money');
                $common_repayment_money = bcdiv($common_repayment_money,100,2);
            }
        }
        $returnData = [
            'amount' => $amount,//已还本金
            'lending_money' => $lending_money,//已还利息
            'manage_money' => $manage_money,//已还贷后管理费
            'money_fines_money' => $money_fines_money,//已还资方罚息
            'common_fines_money' => $common_fines_money,//已还公共罚息
            'month_money' => $month_money,//已还月保费
            'money_repayment_money' => $money_repayment_money,//如果是提前结清,已还资方提前结清手续费
            'common_repayment_money' => $common_repayment_money,//如果是提前结清,已还平台提前结清手续费
            'discount_amount' =>$recordInfo->common->discount_amount//获取折扣金额

        ];
        //已还总金额
        $returnData['all_money'] = $returnData['amount'] + $returnData['lending_money'] + $returnData['manage_money'] + $returnData['money_fines_money'] + $returnData['common_fines_money'] + $returnData['month_money'];
        return $returnData;
    }

    /**
     * Description:如果当期没有还,可用此方法获取各种金额
     * Author:lijiafei
     * @param RepayRecord $recordInfo model
     * @return mixed
     */
    public static function getRepayMoney(RepayRecordModel $recordInfo)
    {
        //应收利息
        $lending_money = bcadd($recordInfo->money->lending_money,$recordInfo->common->lending_money,2);
        //应收总金额
        $all_money = 0;//应收总金额 本金+资方利息+资方罚息+资方手续费+公共利息+公共罚息+贷后管理费+月保费
        $all_money = bcadd(bcadd(bcadd(bcadd(bcadd($all_money,$recordInfo->amount,2),
            $recordInfo->month->amount,2),
            $lending_money,2),
            $recordInfo->money->repayment_money,2),
            $recordInfo->common->manage_money,2);
        //计算罚息
        $summary = self::select('id','rate','amount','loan_id','period')->find($recordInfo->summary_id);
        $fines_money = self::getFines($recordInfo->normal_date,$summary->rate['fines_rate'],$summary->amount,$recordInfo->common->id);
        $all_money = bcadd($all_money,$fines_money['fines_money'],2);
        //资方提前结清手续费
        $repaymentMoney = self::getRepaymentPlan($summary->loan_id,$summary->id);//todo
        $money_repayment_money = bcadd(bcadd($repaymentMoney['repayment_money'],$repaymentMoney['lending_money'],2),$repaymentMoney['fines_money'],2);//资方提前结清手续费
        $repaymentCommon = Repay::repaymentMoney($summary->period,$summary->id);//todo
        $common_repayment_money = bcsub($repaymentCommon,$money_repayment_money,2);//平台提前结清手续费
        $returnData = [
            'all_money' => $all_money, //还款总金额
            'amount' => $recordInfo->amount,//本金
            'lending_money' => $lending_money, //利息
            'manage_money' => $recordInfo->common->manage_money, //贷后管理费
            'money_repayment_money' => $money_repayment_money, //资方提前还清手续费
            'common_repayment_money' => $common_repayment_money,//平台提前还清手续费
            'money_fines_money' => $fines_money['money_fines_money'],//资方罚息
            'common_fines_money' => $fines_money['common_fines_money'],//平台罚息
            'month_money' => $recordInfo->month->amount,//月保费
        ];
        return $returnData;
    }

    /**
     * Description:获取剩余未还金额
     * Author:tianping
     * @param RepayRecord $recordInfo model
     * @return mixed
     */
    public static function getNotRepayAmount(RepayRecordModel $recordInfo){
        //调用已还内置方法
        $repayOkAmount=self::getYihuanMoney($recordInfo)['all_money'];
        //调用未还内置方法
        $notRepayAmount=$recordInfo->period==0?0:self::getRepayMoney($recordInfo)['all_money'];
        $amount=round(($notRepayAmount-$repayOkAmount),2);
        return $amount>=0?$amount:0;

    }

    /**
     * Description: 获取订单/单期还款总金额(不包含提前结清手续费)
     * Author: Gxs
     * @param \App\Models\RepaySummary $summary
     * @param int $period 0为订单总金额, 0 < $period < 12 查单期
     * @param string $type total:订单总额, month:月保总额, money:资方总额, common:公共总额, lending:利息费,
     *                     fines:罚息费, manage:管理费, repayment:提前结清费 fines_money 资方罚息 fines_common 公共罚息
     *                  可扩展
     * @return int|string
     */
    public static function getOrderTotalMoney($summary, $period = 0, $type = 'total')
    {
        $result = 0;
        if (empty($summary))
            return $result;
        $money_collection = $summary->money;
        if ($period > 0) {
            $single = $summary->recordMany->where('period', '=', $period)->first();
            if (empty($single))
                return $result;
            $amount = $summary->recordMany->where('period', '=', $period)->first()->amount; //单期本金
            $sign = '=';
        } else {
            $amount = $summary->amount; //总本金
            $sign = '<>';
        }
        $lending_money = $money_collection->where('period', $sign, $period)->sum('lending_money');
        $fines_money = $money_collection->where('period', $sign, $period)->sum('fines_money');
        $manage_money = $money_collection->where('period', $sign, $period)->sum('manage_money');
        $repayment_money = $money_collection->where('period', $sign, $period)->sum('repayment_money');
        $money_total = bcadd(bcadd(bcadd($lending_money, $fines_money, 2), $manage_money, 2), $repayment_money, 2);
        $common_collection = $summary->common;
        $lending_common = $common_collection->where('period', $sign, $period)->sum('lending_money');
        $fines_common = $common_collection->where('period', $sign, $period)->sum('fines_money');
        $manage_common = $common_collection->where('period', $sign, $period)->sum('manage_money');
        $repayment_common = $common_collection->where('period', $sign, $period)->sum('repayment_money');
        $common_total = bcadd(bcadd(bcadd($lending_common, $fines_common, 2), $manage_common, 2), $repayment_common, 2);
        $month_amount = $summary->month->where('period', $sign, $period)->sum('amount');
        $result = 0;
        switch ($type) {
            case 'total':
                $result = bcadd(bcadd(bcadd($amount, $money_total, 2), $common_total, 2), $month_amount, 2);
                break;
            case 'month':
                $result = $month_amount;
                break;
            case 'money':
                $result = $money_total;
                break;
            case 'common':
                $result = $common_total;
                break;
            case 'lending':
                $result = bcadd($lending_money, $lending_common, 2);
                break;
            case 'fines':
                $result = bcadd($fines_money, $fines_common, 2);
                break;
            case 'fines_money':
                $result = $fines_money;
                break;
            case 'fines_common':
                $result = $fines_common;
                break;
            case 'manage':
                $result = bcadd($manage_money, $manage_common, 2);
                break;
            case 'repayment':
                $result = bcadd($repayment_money, $repayment_common, 2);
                break;
        }
        return $result;
    }
}